package first_practice;

import java.awt.font.NumericShaper;

/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-238-除自身以外数组的乘积
 * @date 2025/3/26 16:27
 */
public class Solution238 {
    /*public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] L = new int[len];
        int[] R = new int[len];
        int[] ans = new int[len];
        L[0] = R[len - 1] = 1;

        for (int i = 1; i < len; i++) {
            L[i] = L[i - 1] * nums[i - 1]; // L[i]表示nums[0]到nums[i-1]元素的累乘
            R[len - 1 - i] = R[len - i] * nums[len - i]; // R[i]表示nums[i+1]到nums[len-1]元素的累乘
        }

        for (int i = 0; i < len; i++) {
            ans[i] = L[i] * R[i];
        }

        return ans;
    }*/

    /**
     * O(1)空间复杂
     *
     * @param nums
     * @return
     */
    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] ans = new int[len];
        ans[0] = 1;

        // left乘积
        for (int i = 1; i < len; i++) {
            ans[i] = ans[i - 1] * nums[i - 1];
        }

        // right乘积
        int R = 1;
        for (int i = len - 1; i >= 0; i--) {
            ans[i] *= R;
            R *= nums[i];
        }

        return ans;
    }
}
